﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;

namespace Lm.Common.Excel
{
    public class ExcelReader
    {
        public DataTable Read(string file)
        {
            string ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + file + ";" +
                    "Extended Properties='Excel 8.0;HDR=no;IMEX=1';";
            var con = new System.Data.OleDb.OleDbConnection(ConnectionString);
            try
            {
                con.Open();
                var tables = con.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { });
                con.Close();
                if (tables.Rows.Count == 0)
                { throw new Exception("Excel必须包含一个表"); }
                var firstTableName = tables.Rows[0]["TABLE_NAME"].ToString();
                System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("select * from [" + firstTableName + "] ", con);
                System.Data.OleDb.OleDbDataAdapter apt = new System.Data.OleDb.OleDbDataAdapter(cmd);
                var dt = new System.Data.DataTable();
                apt.Fill(dt);
                if (dt.Rows.Count < 2)
                { throw new Exception("表必须包含数据"); }
                var headRow = dt.Rows[0];
                foreach (DataColumn c in dt.Columns)
                {
                    var headValue = (headRow[c.ColumnName] == DBNull.Value || headRow[c.ColumnName] == null) ? "" : headRow[c.ColumnName].ToString().Trim();
                    if (headValue.Length == 0)
                    { throw new Exception("必须输入列标题"); }
                    if (Regex.IsMatch(headValue, "^[\u4e00-\u9fa5,a-z,A-Z]{0,}$") == false)
                    { throw new Exception("列标题只能输入汉字或英文字母:" + headValue); }
                    if (dt.Columns.Contains(headValue))
                    { throw new Exception("不能用重复的列标题：" + headValue); }
                    c.ColumnName = headValue;
                }
                dt.Rows.RemoveAt(0);
                return dt;
            }
            catch (Exception ee)
            { throw ee; }
            finally
            { con.Close(); }
        }

    }
}
